import 'dart:math' as math;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_widgets/resources/images.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_widgets/widgets/seekbar/seek_bar.dart';

import '../../config/kq_global.dart';

/// SeekBar的二次封装，添加了文本的显示
class KqSeekBar extends StatefulWidget {
  /// seekbar的值的回调
  final void Function(int one, int two)? callback;

  /// 是否是双滑块，默认为否
  final bool isTwoSeekBar;

  /// 第一个seekbar位置
  final double? valueOneSeekBar;

  /// 第二个seekbar位置
  final double? valueTwoSeekBar;

  /// 进度条最大值
  final double max;

  ///背景进度颜色
  final Color bgColor;

  ///只有一个seekbar的进度颜色
  final Color oneSeekColor;

  ///有两个seekbar时第二个进度的颜色
  final Color twoSeekColor;

  /// 高度
  final double? height;

  /// 进度条高度
  final double? progressHeight;

  /// 是否展示进度文本
  final bool showSeekBarText;

  /// 是否展示在进度文本上方
  final bool isShowSeekBarTextOnTop;

  final double? fontSize;

  final Color? textColor;

  /// 文本偏移量
  final double? textOffset;

  /// 第一个seekbar的进度
  final String? Function(int progress)? oneTextFormat;

  /// 第二个seekbar的进度
  final String? Function(int progress)? twoTextFormat;

  const KqSeekBar({
    super.key,
    this.callback,
    this.isTwoSeekBar = false,
    this.valueOneSeekBar,
    this.valueTwoSeekBar,
    this.max = 100,
    this.bgColor = KqThemeColors.bgF5,
    this.oneSeekColor = KqThemeColors.textLightBlue,
    this.twoSeekColor = KqThemeColors.bgF5,
    this.height,
    this.progressHeight,
    this.showSeekBarText = false,
    this.isShowSeekBarTextOnTop = false,
    this.oneTextFormat,
    this.twoTextFormat,
    this.fontSize,
    this.textColor,
    this.textOffset,
  });

  @override
  State<StatefulWidget> createState() => KqSeekBarState();
}

class KqSeekBarState extends State<KqSeekBar> {
  double oneProgress = 0;

  double secondProgress = 0;

  update() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    oneProgress = widget.valueOneSeekBar ?? 0;
    secondProgress = widget.valueTwoSeekBar ?? 0;
  }

  @override
  void didUpdateWidget(covariant KqSeekBar oldWidget) {
    super.didUpdateWidget(oldWidget);
    oneProgress = widget.valueOneSeekBar ?? 0;
    secondProgress = widget.valueTwoSeekBar ?? 0;
  }

  @override
  Widget build(BuildContext context) {
    return widget.showSeekBarText
        ? Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (widget.isShowSeekBarTextOnTop) showText(),
              getSeekBar(),
              if (!widget.isShowSeekBarTextOnTop) showText(),
            ],
          )
        : getSeekBar();
  }

  Widget getSeekBar() {
    return SeekBar(
      callback: (one, two) {
        oneProgress = one;
        secondProgress = two;
        widget.callback?.call(one.toInt(), two.toInt());
        update();
      },
      isTwoSeekBar: widget.isTwoSeekBar,
      valueOneSeekBar: oneProgress,
      valueTwoSeekBar: secondProgress,
      max: widget.max,
      bgColor: widget.bgColor,
      oneSeekColor: widget.oneSeekColor,
      twoSeekColor: widget.twoSeekColor,
      oneSeekWidget: KqImage.assets(
        url: Images.commonIcHuakuai28,
        package: KqGlobal.packageName,
        width: widget.height ?? 44.r,
        height: widget.height ?? 44.r,
      ),
      twoSeekWidget: KqImage.assets(
        url: Images.commonIcHuakuai28,
        package: KqGlobal.packageName,
        width: widget.height ?? 44.r,
        height: widget.height ?? 44.r,
      ),
      height: widget.height ?? 44.r,
      progressHeight: widget.progressHeight ?? 4.r,
    );
  }

  Widget showText() {
    return LayoutBuilder(builder: (context, constraints) {
      var max = widget.max;
      double width = constraints.maxWidth;
      double padding = widget.height ?? 44.r;
      double progressWidth = width - padding;
      String textOne = widget.oneTextFormat?.call(oneProgress.toInt()) ??
          oneProgress.toInt().toString();
      double textOneWidth = paintWidthWithTextStyle(textOne, width);
      double leftOne = progressWidth * oneProgress / max -
          (textOneWidth / 2) +
          (padding / 2);
      String? textTwo;
      double? textTwoWidth;
      double? leftTwo;
      if (widget.isTwoSeekBar) {
        textTwo = widget.twoTextFormat?.call(secondProgress.toInt()) ??
            secondProgress.toInt().toString();
        textTwoWidth = paintWidthWithTextStyle(textTwo, width);
        leftTwo = progressWidth * secondProgress / max -
            (textTwoWidth / 2) +
            (padding / 2);
      }
      double height = math.max(paintHeightWithTextStyle(textOne),
          paintHeightWithTextStyle(textTwo ?? ''));
      return Container(
        height: height,
        width: width,
        margin: EdgeInsets.only(
            top: widget.isShowSeekBarTextOnTop ? 0 : widget.textOffset ?? 0,
            bottom: widget.isShowSeekBarTextOnTop ? widget.textOffset ?? 0 : 0),
        child: Stack(
          children: [
            Positioned(
                left: leftOne,
                child: Text(
                  textOne,
                  style: TextStyle(
                    color: widget.textColor ?? KqThemeColors.text26,
                    fontSize: widget.fontSize ?? 12.sp,
                  ),
                )),
            if (widget.isTwoSeekBar)
              Positioned(
                  left: leftTwo,
                  child: Text(
                    textTwo ?? '',
                    style: TextStyle(
                      color: widget.textColor ?? KqThemeColors.text26,
                      fontSize: widget.fontSize ?? 12.sp,
                    ),
                  )),
          ],
        ),
      );
    });
  }

  /// 计算内容宽度
  double paintWidthWithTextStyle(String text, double maxWidth) {
    final TextPainter textPainter = TextPainter(
        text: TextSpan(
            text: text,
            style: TextStyle(
              fontSize: widget.fontSize ?? 12.sp,
            )),
        textDirection: TextDirection.ltr,
        maxLines: 1)
      ..layout(minWidth: 0, maxWidth: maxWidth);
    return textPainter.size.width;
  }

  /// 计算内容高度
  double paintHeightWithTextStyle(String text) {
    final TextPainter textPainter = TextPainter(
        text: TextSpan(
            text: text,
            style: TextStyle(
              fontSize: widget.fontSize ?? 12.sp,
            )),
        textDirection: TextDirection.ltr,
        maxLines: 1)
      ..layout();
    return textPainter.size.height;
  }
}
